<template>
  <view class="learn-container">
    <view class="header">
      <text class="title">背单词</text>
    </view>
    
    <view class="word-card" v-if="currentWord && !isComplete">
      <view class="word-content">
        <text class="word">{{ currentWord.word }}</text>
        <text class="phonetic">{{ currentWord.pronunciation }}</text>
      </view>
      
      <view class="options-container">
        <view 
          v-for="(option, index) in currentOptions" 
          :key="index"
          class="option-item"
          :class="{
            'selected': selectedOption === index,
            'correct': showAnswer && option.isCorrect,
            'wrong': showAnswer && selectedOption === index && !option.isCorrect
          }"
          @click="selectOption(index)"
        >
          <text class="option-text">{{ option.text }}</text>
        </view>
      </view>
      
      <view class="answer-area" v-if="showAnswer">
        <text class="meaning">{{ currentWordMeaning }}</text>
        <view class="examples" v-if="currentWordExamples.length > 0">
          <text class="examples-title">例句：</text>
          <view v-for="(example, index) in currentWordExamples" :key="index" class="example-item">
            <text class="example-en">{{ example.en }}</text>
            <text class="example-cn">{{ example.cn }}</text>
          </view>
        </view>
      </view>
      
      <view class="progress">
        <text class="progress-text">
          进度: {{ currentIndex + 1 }}/{{ totalWordCount }} 
          (剩余错词: {{ wrongWords.length }})
        </text>
        <progress :percent="progressPercent" stroke-width="6" />
      </view>
      
      <view class="actions">
        <button 
          class="btn next" 
          @click="nextWord" 
          :disabled="!showAnswer"
          :class="{ 'disabled': !showAnswer }"
        >
          {{ showAnswer ? '下一个' : '请选择答案' }}
        </button>
      </view>
    </view>
    
    <view class="complete" v-else-if="isComplete">
      <text class="complete-text">今日学习完成！</text>
      <text class="complete-stats">正确率: {{ Math.round((correctCount / totalAnswered) * 100) }}%</text>
      <text class="complete-detail">总单词: {{ totalWordCount }} | 正确: {{ correctCount }} | 错误: {{ wrongCount }}</text>
      
      <view class="word-stats" v-if="wordStatistics.length > 0">
        <text class="stats-title">单词统计：</text>
        <view v-for="stat in wordStatistics.slice(0, 5)" :key="stat.vocabularyId" class="stat-item">
          <text class="stat-word">{{ getWordById(stat.vocabularyId)?.word }}</text>
          <text class="stat-count">✓{{ stat.correctCount }} ✗{{ stat.incorrectCount }}</text>
        </view>
        <text v-if="wordStatistics.length > 5" class="more-stats">... 还有 {{ wordStatistics.length - 5 }} 个单词</text>
      </view>
      
      <button class="btn-back" @click="goBack">返回</button>
    </view>
    
    <view class="loading" v-else>
      <text>加载中...</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { api } from '@/api';
import { storageAsync } from '../../utils';

const libraryId = ref(null);
const studyCount = ref(20);
const currentIndex = ref(0);
const words = ref([]);
const wrongWords = ref([]); // 存储答错的单词
const currentWord = ref(null);
const isComplete = ref(false);
const selectedOption = ref(null);
const showAnswer = ref(false);
const correctCount = ref(0);
const wrongCount = ref(0);
const totalAnswered = ref(0);
const currentOptions = ref([]);
const wordStatistics = ref([]); // 单词统计数组
var mode = "learn";

// 计算属性
const progressPercent = computed(() => {
  return ((currentIndex.value + 1) / totalWordCount.value) * 100;
});

const totalWordCount = computed(() => {
  return words.value.length + wrongWords.value.length;
});

const currentWordMeaning = computed(() => {
  if (!currentWord.value) return '';
  const translations = currentWord.value.translations || [];
  if (translations.length > 0) {
    return `${translations[0].pos} ${translations[0].cn}`;
  }
  return currentWord.value.translation || '';
});

const currentWordExamples = computed(() => {
  if (!currentWord.value) return [];
  const sentences = currentWord.value.sentences || [];
  return sentences.map(sentence => ({
    en: sentence.content,
    cn: sentence.cn
  }));
});

// 页面加载
onMounted(async () => {
  await loadLibraryInfo();
});

// 加载词书信息
const loadLibraryInfo = async () => {
  try {
    const library = await storageAsync.get('currentLibrary');
    if (library) {
		mode="learn";
      libraryId.value = library.id;
      studyCount.value = library.studyCount || 20;
      console.log('加载词书信息:', library);
		await loadWords();
    }
	const review = await storageAsync.get('reviewWords');
	if (review) {
		mode="review";
	  words.value = review;
	  initWordStatistics();
	  console.log('加载复习单词:', review);
	  if (words.value.length > 0) {
	    setCurrentWord(0);
	  } else {
	    uni.showToast({
	      title: '暂无单词数据',
	      icon: 'none'
	    });
	  }
	}
  } catch (error) {
    console.error('加载词书信息失败:', error);
  }
};

// 加载单词数据
const loadWords = async () => {
  try {
    console.log('开始加载单词，数量:', studyCount.value, '词书ID:', libraryId.value);
    
    const response = await api.vocab.getLearnVocabs(studyCount.value, libraryId.value);
    words.value = response.data.words || [];
    
    // 初始化单词统计
    initWordStatistics();
    
    console.log('加载到的单词:', words.value);
    
    if (words.value.length > 0) {
      setCurrentWord(0);
    } else {
      uni.showToast({
        title: '暂无单词数据',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('加载单词失败:', error);
    uni.showToast({
      title: '加载单词失败',
      icon: 'none'
    });
  }
};

// 初始化单词统计
const initWordStatistics = () => {
  wordStatistics.value = words.value.map(word => ({
    vocabularyId: word.id,
    word: word.word,
    correctCount: 0,
    incorrectCount: 0
  }));
};

// 根据ID获取单词
const getWordById = (vocabularyId) => {
  return words.value.find(word => word.id === vocabularyId);
};

// 更新单词统计
const updateWordStatistics = (vocabularyId, isCorrect) => {
  const stat = wordStatistics.value.find(stat => stat.vocabularyId === vocabularyId);
  if (stat) {
    if (isCorrect) {
      stat.correctCount++;
    } else {
      stat.incorrectCount++;
    }
  } else {
    // 如果是错词列表中的单词（不在初始列表中）
    wordStatistics.value.push({
      vocabularyId: vocabularyId,
      word: currentWord.value.word,
      correctCount: isCorrect ? 1 : 0,
      incorrectCount: isCorrect ? 0 : 1
    });
  }
};

// 设置当前单词和选项
const setCurrentWord = (index) => {
  // 优先从错词列表中取单词
  if (wrongWords.value.length > 0 && index >= words.value.length) {
    const wrongIndex = index - words.value.length;
    currentWord.value = wrongWords.value[wrongIndex];
  } else {
    currentWord.value = words.value[index];
  }
  
  selectedOption.value = null;
  showAnswer.value = false;
  generateOptions();
};

// 生成选项（1个正确答案 + 3个干扰项）
const generateOptions = () => {
  if (!currentWord.value) return;
  
  const correctAnswer = currentWordMeaning.value;
  const options = [{ text: correctAnswer, isCorrect: true }];
  
  // 从其他单词中随机选择3个干扰项
  const allWords = [...words.value, ...wrongWords.value];
  const otherWords = allWords.filter(word => word.id !== currentWord.value.id);
  const shuffledWords = [...otherWords].sort(() => Math.random() - 0.5).slice(0, 3);
  
  shuffledWords.forEach(word => {
    const translations = word.translations || [];
    let meaning = '';
    if (translations.length > 0) {
      meaning = `${translations[0].pos} ${translations[0].cn}`;
    } else {
      meaning = word.translation || '';
    }
    if (meaning && meaning !== correctAnswer) {
      options.push({ text: meaning, isCorrect: false });
    }
  });
  
  // 如果干扰项不足，补充一些默认选项
  while (options.length < 4) {
    options.push({ 
      text: `选项${options.length}`, 
      isCorrect: false 
    });
  }
  
  // 随机打乱选项顺序
  currentOptions.value = options.sort(() => Math.random() - 0.5);
};

// 选择选项
const selectOption = (index) => {
  if (showAnswer.value) return;
  
  selectedOption.value = index;
  showAnswer.value = true;
  totalAnswered.value++;
  
  const isCorrect = currentOptions.value[index].isCorrect;
  
  // 更新统计
  if (isCorrect) {
    correctCount.value++;
  } else {
    wrongCount.value++;
    // 将答错的单词添加到错词列表
    if (!wrongWords.value.find(word => word.id === currentWord.value.id)) {
      wrongWords.value.push(currentWord.value);
    }
  }
  
  // 更新单词统计
  updateWordStatistics(currentWord.value.id, isCorrect);
};

// 下一个单词
const nextWord = async () => {
  if (!showAnswer.value) {
    uni.showToast({
      title: '请先选择答案',
      icon: 'none'
    });
    return;
  }
  
  currentIndex.value++;
  
  // 检查是否完成所有单词（包括错词）
  if (currentIndex.value < totalWordCount.value) {
    setCurrentWord(currentIndex.value);
  } else {
    isComplete.value = true;
    
    // 输出最终的单词统计
    console.log('单词统计结果:', wordStatistics.value);
	const userInfo = await storageAsync.get("userInfo");
	if(mode=="learn"){
		await api.vocab.recordLearnVocabs(userInfo.id,libraryId.value,wordStatistics.value)
		uni.showToast({
		  title: '学习完成！',
		  icon: 'success'
		});
	}else{
		await api.vocab.recordReviewVocabs(userInfo.id,wordStatistics.value)
		uni.showToast({
		  title: '复习完成！',
		  icon: 'success'
		});
	}
    
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
</script>

<style scoped>
.learn-container {
  padding: 20px;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: white;
}

.back-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
  border-radius: 8px;
  padding: 8px 16px;
  font-size: 14px;
}

.word-card {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.word-content {
  text-align: center;
  margin-bottom: 30px;
}

.word {
  display: block;
  font-size: 32px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.phonetic {
  display: block;
  font-size: 16px;
  color: #666;
}

.options-container {
  margin-bottom: 20px;
}

.option-item {
  padding: 15px;
  margin-bottom: 12px;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  background: white;
  transition: all 0.3s ease;
}

.option-item.selected {
  border-color: #2196F3;
  background: #f0f8ff;
}

.option-item.correct {
  border-color: #4CAF50;
  background: #f0fff0;
}

.option-item.wrong {
  border-color: #F44336;
  background: #fff0f0;
}

.option-text {
  font-size: 16px;
  color: #333;
}

.answer-area {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 12px;
  margin-bottom: 20px;
}

.meaning {
  display: block;
  font-size: 18px;
  font-weight: bold;
  color: #4CAF50;
  margin-bottom: 12px;
}

.examples {
  margin-top: 10px;
}

.examples-title {
  display: block;
  font-size: 14px;
  font-weight: bold;
  color: #666;
  margin-bottom: 8px;
}

.example-item {
  margin-bottom: 10px;
  padding: 8px;
  background: white;
  border-radius: 6px;
}

.example-en {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
}

.example-cn {
  display: block;
  font-size: 13px;
  color: #666;
}

.progress {
  margin-bottom: 20px;
}

.progress-text {
  display: block;
  text-align: center;
  color: #666;
  margin-bottom: 8px;
  font-size: 14px;
}

.actions {
  display: flex;
  gap: 15px;
}

.btn {
  flex: 1;
  padding: 15px;
  border: none;
  border-radius: 10px;
  font-size: 16px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.btn.next {
  background: #2196F3;
  color: white;
}

.btn.next.disabled {
  background: #ccc;
  color: #666;
}

.complete {
  background: white;
  border-radius: 16px;
  padding: 40px 30px;
  text-align: center;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.complete-text {
  display: block;
  font-size: 24px;
  font-weight: bold;
  color: #4CAF50;
  margin-bottom: 10px;
}

.complete-stats {
  display: block;
  font-size: 18px;
  color: #2196F3;
  margin-bottom: 8px;
}

.complete-detail {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 20px;
}

.word-stats {
  margin: 20px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 10px;
}

.stats-title {
  display: block;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #e0e0e0;
}

.stat-item:last-child {
  border-bottom: none;
}

.stat-word {
  font-size: 14px;
  color: #333;
}

.stat-count {
  font-size: 13px;
  color: #666;
}

.more-stats {
  display: block;
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  text-align: center;
}

.btn-back {
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 10px;
  padding: 12px 24px;
  font-size: 16px;
}

.loading {
  text-align: center;
  color: white;
  font-size: 18px;
  margin-top: 50px;
}
</style>